﻿using System;
using System.Drawing;
using System.Windows.Forms;

namespace TxtNumeric {

	public class cmb : ComboBox {

		public bool IsTextEmpty() {
			return string.IsNullOrEmpty( base.Text );
		}

		protected override void OnEnter( EventArgs e ) {
			base.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems;
			base.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend;
			base.OnEnter( e );
		}

		public bool C_OnlyNumbers { get; set; }

		public bool C_ShowRedOnLeaveIfEmpty { get; set; }

		private bool NumberEntered;

		private bool CheckIfNumericKey( Keys K, bool isDecimalPoint ) {
			if ( K == Keys.Back ) //backspace?
				return true;

			else if ( K == Keys.OemPeriod || K == Keys.Decimal )  //decimal point?
				return isDecimalPoint ? false : true;       //or: return !isDecimalPoint
			else if ( ( K >= Keys.D0 ) && ( K <= Keys.D9 ) )      //digit from top of keyboard?
				return true;
			else if ( ( K >= Keys.NumPad0 ) && ( K <= Keys.NumPad9 ) )    //digit from keypad?
				return true;
			else
				return false;   //no "numeric" key
		}

		protected override void OnLeave( EventArgs e ) {
			if ( base.SelectedIndex == -1 && C_ShowRedOnLeaveIfEmpty == true ) {
				base.BackColor = Color.Red;
			} else {
				base.BackColor = Color.Empty;
			}

			base.OnLeave( e );
		}

		protected override void OnKeyPress( KeyPressEventArgs e ) {
			if ( C_OnlyNumbers == true ) {
				if ( NumberEntered == false ) {
					e.Handled = true;
				}
			}
			base.OnKeyPress( e );
		}

		protected override void OnKeyDown( KeyEventArgs e ) {
			NumberEntered = CheckIfNumericKey( e.KeyCode, false );
			base.OnKeyDown( e );
		}
	}
}